package com.it.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.aiInsureOrder.OrderApi;
import com.it.entity.report.AiClaimReport;
import com.it.entity.insure.AiInsureOrder;
import com.it.mapper.AiClaimReportMapper;
import com.it.service.AiClaimReportService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.untils.ReportIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import utils.R;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 农户报案表（灾祸发生后报案记录） 服务实现类
 * </p>
 *
 * @author sunwz
 * @since 2025年09月19日
 */
@Service
public class AiClaimReportServiceImpl extends ServiceImpl<AiClaimReportMapper, AiClaimReport> implements AiClaimReportService {
    @Autowired
    private AiClaimReportMapper aiClaimReportMapper;

    @Autowired
    private OrderApi orderApi;

    @Override
    public R addReport(AiClaimReport aiClaimReport) {
        //生成唯一reportId：增加重试次数限制，避免死循环；优化空判逻辑
        String reportId = ReportIdGenerator.generateReportId();
        if (reportId == null) {
            return R.Failed("报案ID生成失败，请稍后重试");
        }
        aiClaimReport.setReportNo(reportId);
        //校验保单号并关联insuredId：优化字符串空判，增加查询结果空防护
        String policyId = aiClaimReport.getPolicyId();
        if (!StringUtils.hasText(policyId)) { // 替代null和""判断，兼容空格场景
            return R.Failed("未输入保单号");
        }
        //查询订单：明确查询条件（orderId=policyId需确认业务逻辑是否正确）

        AiInsureOrder insureOrder = orderApi.getOrderByPolicyId(policyId);
        if (insureOrder == null) { // 新增：查询不到订单时返回明确错误
            return R.Failed("保单号不存在，保单号：" + policyId);
        }
        aiClaimReport.setInsuredId(insureOrder.getInsuredId());
        String workNo = aiClaimReport.getReportWorkNo();
        if (!StringUtils.hasText(workNo)) {
            return R.Failed("未输入员工工号");
        }
        // 补充默认值：设置报案时间（原代码仅设handleTime，可能遗漏reportTime）
        aiClaimReport.setReportTime(LocalDateTime.now()); // 报案提交时间
        aiClaimReport.setHandleTime(LocalDateTime.now()); // 处理时间（初始可设为提交时间）
        aiClaimReport.setReportStatus(1); // 新增：默认报案状态（如“待处理”，需按业务定义）
        //  插入数据：建议捕获异常（可选，视全局异常处理配置）
        try {
            aiClaimReportMapper.insert(aiClaimReport);
            return R.Success("添加成功", reportId); // 返回reportId，方便前端后续操作
        } catch (Exception e) {
            // 日志记录异常（需注入Logger）
            // log.error("新增报案失败，报案信息：{}", aiClaimReport, e);
            return R.Failed("添加失败：" + e.getMessage());
        }
    }

    @Override
    public R selectPage(int pageNum, int pageSize, String policyId, Integer reportStatus) {
        PageHelper.startPage(pageNum,pageSize);
        LambdaQueryWrapper<AiClaimReport> wrapper =new LambdaQueryWrapper<>();
        if (policyId!=null&&policyId!=""){
            wrapper.eq(AiClaimReport::getPolicyId,policyId);}
        if (reportStatus!=null){
            wrapper.eq(AiClaimReport::getReportStatus,reportStatus);}
        List<AiClaimReport> list = aiClaimReportMapper.selectList(wrapper);
        return R.Success("查询成功",new PageInfo<>(list));
    }

    @Override
    public R selectById(String reportNo) {
        LambdaQueryWrapper<AiClaimReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiClaimReport::getReportNo,reportNo);
        AiClaimReport aiClaimReport = aiClaimReportMapper.selectOne(wrapper);
        if (aiClaimReport != null){
            return R.Success("查询成功",aiClaimReport);
        }
        return R.Failed("无符合条件的报案信息");
    }



    @Override
    public R selectByPolicyIdAndTime(String policyId, LocalDateTime reportTime) {
        LambdaQueryWrapper<AiClaimReport> wrapper =new LambdaQueryWrapper<>();
        wrapper.eq(AiClaimReport::getPolicyId,policyId);
        wrapper.eq(AiClaimReport::getReportTime,reportTime);
        AiClaimReport aiClaimReport = aiClaimReportMapper.selectOne(wrapper);
        if (aiClaimReport!=null&&!"".equals(aiClaimReport)){
            return R.Failed("已经报告过该事件");
        }
        return R.Success("事件重复检验通过");
    }

    @Override
    public R update(String reportNo, Integer reportStatus) {

        aiClaimReportMapper.update(reportNo,reportStatus);

        return null;
    }

    @Override
    public R dispatchUpdate(String reportNo, Integer reportStatus, Integer workOutStatus) {
        aiClaimReportMapper.dispatchUpdate(reportNo,reportStatus,workOutStatus);
        return null;
    }

    @Override
    public R selectDispatch(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        LambdaQueryWrapper<AiClaimReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiClaimReport::getReportStatus,1).or().eq(AiClaimReport::getWorkOutStatus,0);
        List<AiClaimReport> list = aiClaimReportMapper.selectList(wrapper);
        return R.Success("查询成功",new PageInfo<>(list));
    }

    @Override
    public AiClaimReport add(AiClaimReport aiClaimReport, BigDecimal lossEstimate) {
        //生成唯一reportId：增加重试次数限制，避免死循环；优化空判逻辑
        String reportId = ReportIdGenerator.generateReportId();
        aiClaimReport.setReportNo(reportId);
        aiClaimReport.setLossEstimate(lossEstimate);
        aiClaimReport.setReportStatus(1);
        aiClaimReportMapper.insert(aiClaimReport);
        return aiClaimReport;

    }

    @Override
    public AiClaimReport getOne(String reportNo) {

        LambdaQueryWrapper<AiClaimReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AiClaimReport::getReportNo,reportNo);

        return aiClaimReportMapper.selectOne(queryWrapper);
    }
}
